import re
from rest_framework.views import APIView,Response
from rest_framework import permissions
from rest_framework.generics import RetrieveAPIView,ListAPIView

from django.conf import settings
from django.core.cache import cache
from utils.response import APIResponse
from utils.common import check_vip_exp
from rest_framework_jwt import authentication

from . import serializers,throttles,models
from libs import tx_sms
from video import models as video_models
from celery_task import send_sms_task


'''登陆'''
class LoginAPIView(APIView):
    # 认证和权限类局部禁用
    authentication_classes = []
    permission_classes = []
    def post(self, request, *args, **kwargs):
        ser_obj = serializers.LoginModelSerializer(data=request.data)
        if not ser_obj.is_valid():
            # 得到序列化抛出的错误信息内容
            msg = list(ser_obj.errors.values())[0][0]
            print(msg)
            return APIResponse(1, msg,data=ser_obj.errors)

        # 判断VIP是否过期
        check_vip_exp(ser_obj.user)

        return APIResponse(results={
            "user_info": {
                "nick_name": ser_obj.user.user_detail.nick_name,
                "icon": f"{settings.BASE_URL}/media/{ser_obj.user.icon}",
                "vip_type": ser_obj.user.get_vip_type_display(),
            },
            "token": ser_obj.token
        })


'''发送验证码'''
class SMSAPIView(APIView):
    # 设置频率校验
    throttle_classes = [throttles.SMSRateThrottle]
    def post(self,request,*args,**kwargs):
        mobile = request.data.get('mobile')

        # 因为re匹配的时候只能匹配字符串，因此转成str
        if isinstance(mobile, int):
            mobile = str(mobile)
        if not (mobile and re.match(r'^1[3-9][0-9]{9}$', mobile)):
            return APIResponse(2, '手机号格式有误')

        # 获取验证码
        code = tx_sms.get_code()
        # 发送验证码接口
        # result = tx_sms.send_sms(mobile, code, settings.SMS_EXP // 60)
        # if not result:
        #     return  APIResponse(1,"验证码发送失败")

        # 使用celery框架完成发送短信验证码
        result = send_sms_task.delay(mobile, code, settings.SMS_EXP // 60)
        print(result)   # id号

        # 设置服务器缓存验证码, key,value,exp
        cache.set(settings.SMS_CACHE_KEY + mobile, code, settings.SMS_EXP)
        # 校验发送的验证码与缓存的验证码是否一致
        print('>>>> %s - %s <<<<' % (code, cache.get(settings.SMS_CACHE_KEY + mobile)))
        return APIResponse(0, '发送验证码成功')


'''注册'''
class RegisterAPIView(APIView):
    # 认证和权限类局部禁用
    authentication_classes = []
    permission_classes = []
    def post(self, request, *args, **kwargs):
        ser_obj = serializers.RegisterModelSerializer(data=request.data)
        if not ser_obj.is_valid():
            # 得到序列化抛出的错误信息内容
            msg = list(ser_obj.errors.values())[0][0]
            print(msg)
            return APIResponse(1, msg,data=ser_obj.errors)

        # 判断VIP是否过期
        check_vip_exp(ser_obj.user)

        return APIResponse(results={
            "user_info": {
                "nick_name": ser_obj.user.user_detail.nick_name,
                "icon": f"{settings.BASE_URL}{settings.MEDIA_URL}{ser_obj.user.icon}",
                "vip_type": ser_obj.user.get_vip_type_display(),
            },
            "token": ser_obj.token
        })


'''手机验证码登陆'''
class MobileLoginAPIView(APIView):
    # 认证和权限类局部禁用
    authentication_classes = []
    permission_classes = []
    def post(self, request, *args, **kwargs):
        # 序列化登陆数据
        ser_obj = serializers.MobileLoginModelSerializer(data=request.data)
        if not ser_obj.is_valid():
            # 得到序列化抛出的错误信息内容
            msg = list(ser_obj.errors.values())[0][0]
            print(msg)
            return APIResponse(1, msg, data=ser_obj.errors)

        # 判断VIP是否过期
        check_vip_exp(ser_obj.user)

        return APIResponse(results={
            "user_info": {
                "nick_name": ser_obj.user.user_detail.nick_name,
                "icon": f"{settings.BASE_URL}/media/{ser_obj.user.icon}",
                "vip_type": ser_obj.user.get_vip_type_display(),
            },
            "token": ser_obj.token
        })


'''获取用户详情'''
class UserDetailAPIView(APIView):
    '''使用jwt的认证模块'''
    # authentication_classes = [authentication.JSONWebTokenAuthentication, ]
    '''权限校验 必须登陆'''
    permission_classes = [permissions.IsAuthenticated]
    def post(self,request, *args, **kwargs):
        queryset = models.User_Detail.objects.filter(user=request.user).first()
        if queryset:
            return Response(
                serializers.UserDetailModelSerializer(queryset, many=False).data
            )
        return APIResponse(1,"erroe")


'''获取用户vip类型'''
class UserVipTypeAPIView(APIView):
    '''权限校验 必须登陆'''
    permission_classes = [permissions.IsAuthenticated]
    def post(self,request, *args, **kwargs):
        queryset = models.User.objects.filter(pk=request.user.pk).first()
        if queryset:
            return Response(serializers.UserVipTypeModelSerializer(queryset).data)
        return APIResponse(1, "erroe")


'''获取用户视频记录'''
class RecordAPIView(APIView):
    '''权限校验 必须登陆'''
    permission_classes = [permissions.IsAuthenticated]
    def post(self,request, *args, **kwargs):
        queryset = video_models.Record.objects.filter(user=request.user).all()
        if queryset:
            return Response(serializers.UserVideoRecordModelSerializer(queryset, many=True).data)
        return APIResponse(1, "erroe")